"""file 操作相关的form"""

from django import forms
from web import models
from django.core.exceptions import ValidationError
from .bootstrap import BootStrapFrom


class FileRepositoryModelForm(BootStrapFrom, forms.ModelForm):
    class Meta:
        model = models.FileRepository
        fields = ['name']

    def __init__(self, request, parent_obj, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.request = request
        self.parent_obj = parent_obj

    # 判断 同一目录下的文件名是否重复
    def clean_name(self):
        file_name = self.cleaned_data.get('name')
        # 判断是否有 parent_obj
        file_queryset = models.FileRepository.objects.filter(file_type=2, name=file_name
                                                             , project=self.request.tracer.project)
        if self.parent_obj:
            file_obj = file_queryset.filter(parent=self.parent_obj).first()
        else:
            file_obj = file_queryset.filter(parent__isnull=True).first()
        if file_obj:
            raise ValidationError('文件夹已存在')
        return file_name


class FileCheckModelForm(forms.ModelForm):
    etag = forms.CharField(label='Etag')

    class Meta:
        model = models.FileRepository
        exclude = ['project', 'file_type', 'update_user', 'update_datetime']

    # 返回完整的file_path
    def clean_file_path(self):
        return "https://%s" % self.cleaned_data.get('file_path')
